<?php
namespace app\modules\controllers;
use Yii;
use yii\web\Controller;
//use yii\data\Pagination;
use app\models\Category;
use yii\db\Exception;

class CategoryController extends Controller
{
    //分类列表
    public function actionList()
    {
        $this->layout='adminlist.php';
        $model=new Category();
        $cates=$model->getTreeList();
//        var_dump($cates);exit;
        return $this->render('cates',['cates'=>$cates]);
    }
    
    public function actionAdd()
    {
        $this->layout='adminlist.php';
        $model=new Category();
        $list=$model->getOptions();
        if(Yii::$app->request->isPost)
        {
            $post= Yii::$app->request->post();
            if($model->add($post)){
                $this->redirect(['category/add']);
                Yii::$app->session->setFlash('info','添加成功');
            }else{
                Yii::$app->session->setFlash('info','添加失败');
            }
        }
        return $this->render('add',['model'=>$model,'list'=>$list]);
    }
    
    public function actionEdit()
    {
        $this->layout='adminlist.php';
        $cateid= Yii::$app->request->get('cateid');
        $model= Category::find()->where('cateid=:id',[':id'=>$cateid])->one();
        $list=$model->getOptions();
        if(Yii::$app->request->isPost)
        {
            $post= Yii::$app->request->post();
            //当做更新操作时，model模型不能新建，否则会重新插入数据
            if($model->load($post) && $model->save()){
                $this->redirect(['category/list']);
                Yii::$app->session->setFlash('info','x修改成功');
            }
        }
        return $this->render('add',['model'=>$model,'list'=>$list]);
    }
    
    public function actionDel()
    {
        try{
        $this->layout='adminlist.php';
        $cateid= Yii::$app->request->get('cateid');
        //判断是否有子类，有的话不能删除
        $data= Category::find()->where('parentid=:id',[':id'=>$cateid])->one();
        if($data){
            throw new Exception('该分类下有子类，不能删除');
        }
        if(!Category::deleteAll('cateid=:id',[':id'=>$cateid]))
        {
            throw new Exception('删除删除失败');
        }
        } catch (Exception $e){
            Yii::$app->session->setFlash('info',$e->getMessage());
        }
        return $this->redirect(['category/list']);
    }
    
    
    
    
    
}

